package com.lagou.edu.mvcframework.servlet;

import com.lagou.edu.mvcframework.annotations.*;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TODO
 *
 * @author chenx
 * @date 2021/4/27
 */
public class MyDispacherServlet extends HttpServlet {
    private Properties properties = new Properties();
    ;
    private List<String> classNames = new ArrayList<>(); // 缓存扫描到的类的 全限定类名
    // ioc容器
    private Map<String, Object> ioc = new HashMap<String, Object>();

    //private Map<String,Method> handlerMapping = now HashMap<>(); // 存储url和Method之间的映射关系

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        String contextConfiglocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfiglocation);
        //2.扫描相关的类，扫描注解
        doScan(properties.getProperty("base-package"));
        //3.初始化bean对象（实现IOC容器，基于注解）
        doInstance();
        //4.实现依赖注入
        doAutowire();
        //5.构件一个HandlerMapping处理器映射器，将配置好的url和method建立映射关系
        initHandlerMapping();
        System.out.println("初始化完成");
    }

    //5.构造一个HandlerMapping处理器映射器
    private void initHandlerMapping() {
        //从ioc容器中获取加了MyRequestMapping注解的属性
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取所有的类型
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(MyController.class)) {//不是一个MyController
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(MyController.class)) {//是一个MyController,获取他的MyRequestMapping
                MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);
                baseUrl = annotation.value();//等同于/demo
            }
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                //方法是否有MyRequestMapping注解
                if (!method.isAnnotationPresent(MyRequestMapping.class)) {
                    continue;//没有，不处理
                }
                //判断该用户是否有访问权限
                //用户的信息是以参数的形式传入给方法的
                MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                String methodUrl = annotation.value();//等同于/query
                String url = baseUrl + methodUrl;
                Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                //计算方法的参数位置信息
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if (parameter.getType() == HttpServletRequest.class) {
                        handler.getParameterIndex().put(parameter.getType().getSimpleName(), i);
                    }
                    if (parameter.getType() == HttpServletResponse.class) {
                        handler.getParameterIndex().put(parameter.getType().getSimpleName(), i);
                    }
                    handler.getParameterIndex().put(parameter.getName(), i);

                }
                handlerMapping.add(handler);

            }
        }
    }

    //4.实现依赖注入
    private void doAutowire() {
        if (ioc.isEmpty()) {
            return;
        }
        // 有对象，再进⾏依赖注⼊处理
        // 遍历ioc中所有对象，查看对象中的字段，是否有@MyAutowired注解，如果有需要维护依赖注⼊关系
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            // 获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            // 遍历判断处理
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i]; // @MyAutowired private IDemoService demoService;
                if (!declaredField.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }
                // 有该注解
                MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);
                String beanName = annotation.value(); // 需要注⼊的bean的id
                if ("".equals(beanName.trim())) {
                    // 没有配置具体的bean id，那就需要根据当前字段类型注⼊（接⼝注⼊） IDemoService
                    beanName = declaredField.getType().getName();
                }
                // 开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //3.初始化bean对象（实现IOC容器，基于注解）
    private void doInstance() {
        if (classNames.size() == 0) return;
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i); // com.lagou.demo.controller.DemoController
                // 反射
                Class<?> aClass = Class.forName(className);
                // 区分controller，区分service'
                if (aClass.isAnnotationPresent(MyController.class)) {
                    // controller的id此处不做过多处理，不取value了，就拿类的⾸字⺟⼩写作为id，保存到ioc中
                    String simpleName = aClass.getSimpleName();//   DemoController
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    // demoController
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(MyService.class)) {
                    MyService annotation = aClass.getAnnotation(MyService.class);
                    //获取注解value值
                    String beanName = annotation.value();
                    // 如果指定了id，就以指定的为准
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        // 如果没有指定，就以类名⾸字⺟⼩写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }
                    // service层往往是有接⼝的，⾯向接⼝开发，此时再以接⼝名为id,放⼊⼀份对象到ioc中，便于后期根据接⼝类型注⼊
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class<?> anInterface = interfaces[j];
                        // 以接⼝的全限定类名作为id放⼊
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.扫描相关的类，扫描注解com.lagou.edu.mvcframework
    private void doScan(String scanPackage) {
        String sanPackagePath = Thread.currentThread().getContextClassLoader().
                getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        // getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(sanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {//是一个package
                //递归
                doScan(scanPackage + "." + file.getName());//com.lagou.edu.mvcframework.controller
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);

            }
        }
    }

    //1.加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // ⾸字⺟⼩写⽅法
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求
        // 根据uri获取到能够处理当前请求的hanlder（从handlermapping中（list））
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 未找到路径：" + req.getRequestURI());
            return;
        }
        Method method = handler.getMethod();
        //方法是否有Security注解
        if(method.isAnnotationPresent(Security.class)){
            Security security = method.getAnnotation(Security.class);
            String securityValue = security.value();//zhangsan,lisi
            String[] securityValues = securityValue.split(",");
            //判断该用户是否有访问权限
            String name = req.getParameter("name");
            if(!Arrays.asList(securityValues).contains(name)){
                resp.getWriter().write("403 forbid permission:" + req.getRequestURI());
                return;
            }
        }
        // 参数绑定
        // 获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 根据上述数组长度创建一个新的数组（参数数组，是要传入反射调用的）
        Object[] parameterValue = new Object[parameterTypes.length];
        //向参数数组中塞值，而且还得保证参数的顺序和方法中形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 遍历request中所有参数  （填充除了request，response之外的参数）
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            String value = StringUtils.join(param.getValue(), ",");//// name=1&name=2 ==>>name [1,2]==>>1,2
            // 如果参数和方法中的参数匹配上了，填充数据
            //这里的参数名称需要借助插件来使名称保持原样，否则就是arg0,arg1,arg2...
            if (!handler.getParameterIndex().containsKey(param.getKey())) {
                continue;
            }
            Integer index = handler.getParameterIndex().get(param.getKey());
            parameterValue[index] = value;
            Integer requestIndex = handler.getParameterIndex().get(HttpServletRequest.class.getSimpleName());
            Integer responseIndex = handler.getParameterIndex().get(HttpServletResponse.class.getSimpleName());
            parameterValue[requestIndex] = req;
            parameterValue[responseIndex] = resp;
            // 最终调用handler的method属性
            try {
                handler.getMethod().invoke(handler.getController(),parameterValue);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String requestURI = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(requestURI);
            if (matcher.matches()) {//匹配成功
                return handler;
            }
        }
        return null;
    }


}
